package com.xiyu.service.repository.medicine;

import com.xiyu.service.model.elder.info.ElderInfoFetcher;
import com.xiyu.service.model.medicine.*;
import com.xiyu.service.vo.health.medicinePlan.MedicinePlanPageQueryInput;
import org.babyfish.jimmer.spring.repository.JRepository;
import org.babyfish.jimmer.Page;
import org.springframework.util.StringUtils;
import java.util.Optional;

public interface HealthMedicinePlanRepository extends JRepository<HealthMedicinePlan, Long> {
    HealthMedicinePlanTable healthMedicinePlanTable = HealthMedicinePlanTable.$;

    default Page<HealthMedicinePlan> pageQuery(MedicinePlanPageQueryInput inputVO){
        return sql().createQuery(healthMedicinePlanTable)
                .whereIf(StringUtils.hasText(inputVO.getName()), () -> healthMedicinePlanTable.elder().name().like(inputVO.getName()))
                .orderBy(healthMedicinePlanTable.id().desc())
                .select(healthMedicinePlanTable.fetch(HealthMedicinePlanFetcher.$.allTableFields().elder(ElderInfoFetcher.$.allTableFields())))
                .fetchPage(inputVO.getPageNo() - 1, inputVO.getPageSize());
    }

    default Optional<HealthMedicinePlan> findDetailById(Long id){
        return sql().createQuery(healthMedicinePlanTable)
                .where(healthMedicinePlanTable.id().eq(id))
                .select(healthMedicinePlanTable.fetch(HealthMedicinePlanFetcher.$.allTableFields()
                        .elder(ElderInfoFetcher.$.allTableFields())
                        .details(HealthMedicinePlanDetailFetcher.$.allTableFields()
                                .medicine(HealthMedicineFetcher.$.allTableFields()))))
                .fetchOptional();
    }

    Optional<HealthMedicinePlan> findByElderId(Long elderId);
}